package com.ssm.wechat.handler;

import com.ssm.wechat.redis.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Log4j2
public class ReceiveTextMsgHandler implements WeChatMsgHandler {

    private static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX = "loginCode"; //login验证码前缀
    @Resource
    private RedisUtil redisUtil;

    @Override
    public WeChatMsgTypeEnum getMsgType() {
        return WeChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> msgMap) {
        log.info("接收到文本消息事件");

        String toUserName = msgMap.get("ToUserName"); //公众号
        String fromUserName = msgMap.get("FromUserName"); //关注者
        String content = msgMap.get("Content"); //用户发送的消息

        //如果发送的不是验证码则返回(后续可对接AI大模型)
        if(!content.equals(KEY_WORD)) {
            return "<xml>\n" +
                    "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                    "  <CreateTime>12345678</CreateTime>\n" +
                    "  <MsgType><![CDATA[text]]></MsgType>\n" +
                    "  <Content><![CDATA[" + "聊天功能对接AI大模型中..." + "]]></Content>\n" +
                    "</xml>\n";
        }

        //生成随机数验证码
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 6; i ++) {
            sb.append(random.nextInt(10));
        }
        String subscribeContent = "您当前的验证码是：" + sb.toString() + "，5分钟内有效";

        //存入redis
        String numKey = redisUtil.buildKey(LOGIN_PREFIX, sb.toString());
        redisUtil.set(numKey, fromUserName, 5L, TimeUnit.MINUTES);

        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + subscribeContent + "]]></Content>\n" +
                "</xml>\n";
        return replyContent;
    }

}
